<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
%>

<link type="text/css" rel="stylesheet" href="<%=path%>/resources/css/system/form.css" />
<link rel="stylesheet" href="<%=path%>/resources/script/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="<%=path%>/resources/script/ztree/js/jquery.ztree.core-3.5.js"></script>
<script type="text/javascript" src="<%=path%>/resources/script/jquery/easyui/easyui-utils.js"></script>
	
<style type="text/css">
/**表格列表总样式*/
.select-table{
	font-size:12px;
	border-collapse:collapse;
}
.select-table .select-th {
	height:28px;
	line-height:28px;
	color:#000000;

	border-bottom:1px solid #39BBF8;
	border-right:1px solid #39BBF8;
	background-color: #F3F8FE;
}
.select-table .select-td {

	border-bottom:1px solid #39BBF8;
	border-right:1px solid #39BBF8;
	background-color: #F3F8FE;
}
.mulit-table {
	width:200px;

}

.mulit-table td{
	height:25px;
	line-height:25px;
	border-bottom:1px solid #CCC;
	background-color: #FFFFFF;
}
</style>	
  <input type="hidden" id="orgType" name="orgType" value=""> 
<!-- 组织、角色、职位人员选择面板 -->
<div id="userSelectorWin" class="easyui-window">
  <div class="easyui-layout" data-options="fit:true">
	<div data-options="region:'center',border:false">
		<table width="100%" border="0" cellspacing="0" cellpadding="0" class="select-table">
		
			<tr>
				<th class="select-th">快速定位</th>
				<td colspan="3" class="select-td">
					<input type="text" name="fastSearchTxt" id="fastSearchTxt" class="edit-input" style="width: 250px;"/>
					<a href="javascript:fastSearch();"  class="easyui-linkbutton" iconCls="icon-search">查询</a>
					<%--
						<input type="text" name="fastSearchTxt" id="fastSearchTxt"
								onkeyup="fastSearchUser();" onfocus="searchInputFocus();"
								onblur="searchInputBlur();" value="请输入人员姓名或者帐号..."
								style="width: 240px;" />
						<div id="fast_user_div" tabindex="0" hidefocus="true" onmouseout="hideFastUser();"
							onmousedown="displayFastUser();" onmouseover="displayFastUser();"
									style="position:absolute;z-index:99;border:1px solid #817F82;background:white;width:238px;display:none;"></div>
						<input type='checkbox' id='promoter' class="toolbar-check" userId="${proInstance.userId}" userName="${proInstance.userName}" orgId="${proInstance.orgId}" />流程发起人
					--%>
				</td>
			</tr>
		
			<tr>
				<td width="30%" style="background-color: #FFFFFF;height:240px;" valign="top" class="select-td">
				 	<div id="leftPanel" class="easyui-panel">
	            		<div id="leftTree" class="ztree" style="/* height:220px; */ overflow:auto;"></div>
	            	</div>
	            </td>
	            <td width="30%" style="background-color: #FFFFFF;" valign="top" class="select-td">
	            	<table id="userTable"></table>
	            </td>
	           	<td width="10%" align="center" class="select-td">
					<input type="button" value="添加"  onclick="addCheckUser();" /><br/><br/>
					<input type="button" value="删除"  onclick="delUser();"/><br>
					<input type="button" value="全删"  onclick="delAllUser();" />
				</td>
				<td width="30%" style="background-color: #FFFFFF;" valign="top" class="select-td">
					<table id="selUserTable"></table>
				</td>
			</tr>
		</table>
	</div>
	<div data-options="region:'south',border:false" style="text-align:center;padding:5px 0;">
		<a class="easyui-linkbutton" data-options="iconCls:'icon-ok'" href="javascript:saveNextUser();">确定</a>
		<a class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" href="javascript:closeWin();" >取消</a>
	</div>
  </div>
</div>

<!-- 用户人员选择面板  -->
<div id="signleUserWin" class="easyui-window">
	<div class="easyui-layout" data-options="fit:true">
		<div data-options="region:'center',border:false">
			<table width="100%" border="0" cellspacing="0" cellpadding="0" class="select-table">
			<!--
				<tr>
					<th class="select-th">快速定位</th>
					<td class="select-td" colspan="2">
						<input type="text" name="users" id="users" style="width: 250px;"/>
						<input type='checkbox' id='signlePromoter' class="toolbar-check" userId="${proInstance.userId}" userName="${proInstance.userName}"/>流程发起人
					</td>
				</tr>
			-->
				<tr>
		            <td class="select-td" width="30%" style="background-color: #FFFFFF;height:220px;" valign="top">
		            	<table id="signleUserTree"></table>
		            </td>
		        	<td class="select-td" width="10%" align="center">
						<input type="button" value="添加"  onclick="addCheckUser();"/><br>
						
						<input type="button" value="全删"  onclick="delAllUser();"/><br>
					</td>
					<td class="select-td" width="30%" style="background-color: #FFFFFF;" valign="top">
						<table id="signleSelUserTree"></table>
					</td>
				</tr>
			</table>
		</div>
		<div data-options="region:'south',border:false" style="text-align:center;padding:5px 0;">
			<a class="easyui-linkbutton" data-options="iconCls:'icon-ok'" href="javascript:signleSaveNextUser('userIds', 'userNames');">确定</a>
			<a class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" href="javascript:signleCloseWin();" >取消</a>
		</div>
	</div>
</div>
<script type="text/javascript">
/**
 * 人员选择器
 * @param {Object} nodeId
 */
var _nodeId = '';
var nodeType = 'task';
var hiddenId = 'userIds';
var fileldId = 'userNames'; 
var targetIndex = "undefinded";//选择列表中被选中行的索引
var _instanceId = '';
var _callback ;
function selectUserAndCallback(_hiddenId, _fileldId, _nodeType, nodeId,callback){
	selectUser(_hiddenId, _fileldId, _nodeType, nodeId);
	_callback = callback;
}

function selectUser(_hiddenId, _fileldId, _nodeType, nodeId){
	
	if(_nodeType=='fork' && !$("#"+nodeId).attr('checked')) {
		return false;
	}
	_nodeId = nodeId||$("#nodeId").val();//145001
	$("#orgType").val(_nodeType);
	hiddenId = _hiddenId;
	fileldId = _fileldId;
	nodeType = _nodeType;
	_instanceId =''|| $('#instanceId').val();
	$('#userTable').datagrid('loadData', { total: 0, rows: [] });
	$('#selUserTable').datagrid('loadData', { total: 0, rows: [] });
	$('#signleSelUserTree').datagrid('loadData', { total: 0, rows: [] });
	
	$.ajax({ 
		type: "POST",
		//url: "node.shtml?method=getNodeActors",
		url: "node/getNodeActors.shtml",
		data:{
			nodeId:_nodeId,
			nodeType :nodeType,
			instanceId : _instanceId
		},
		success: function(result){
			if(result != null && result.length > 0){
				var rootText = null;
				if(rootText == null){
					if(result[0].ACTOR_TYPE=='1'){
						$('#leftPanel').panel({title:'组织机构',fit:true, border:false});
						selectUserWin(result);
						setSelUser();
						if($('#'+hiddenId).attr("start")=='0'){
							clearAll();
						}
					} else if(result[0].ACTOR_TYPE=='2') {
						$('#leftPanel').panel({title:'角色列表',fit:true, border:false});
						selectUserWin(result);
						setSelUser();
						if($('#'+hiddenId).attr("start")=='0'){
							clearAll();
						}
					} else if(result[0].ACTOR_TYPE=='3') {
						openSignleUserWin(result);//用户列表
						setSelSignUser();
						if($('#'+hiddenId).attr("start")=='0'){
							clearAll();
						}
					} 
				}
			} else {
				alert('未分配办理人无法选择');
			}
		}
	});

}

//组织、角色、职位人员选择面板
var leftTree = null;
var leftSetting = {
	async: {
		enable: true,
		autoParam:['id'],
		//otherParam:{"id":"-1"}
		type:"post",
		url:"ztreePlatform.shtml?method=orgTree"
	},
	callback: {
		onClick: function(event, treeId, treeNode, clickFlag){
			//alert('treeNode.id=='+treeNode.id+'treeNode.type=='+treeNode.type);
			$("#userTable").egrid('reload',{
				'type':treeNode.type,
				 id :treeNode.id,
				 orgType:$("#orgType").val()
			});
			
		}
	}
	
};

function destoryTree(){
	leftTree = null;
	$("#userTable").datagrid('reload');
	$("#selUserTable").datagrid('reload');
}


function selectUserWin(result){

	if(nodeType == 'task' && (_nodeId != $("#nodeId").val())){
		destoryTree();
	} else if(nodeType == 'fork' && (_nodeId != $("#forkNodeId").val())){
		destoryTree();
	}
	
	leftTree = $.fn.zTree.init($("#leftTree"), leftSetting);
	for(var i=0; i < result.length; i++){
		leftTree.addNodes(null, {
			id:result[i].ACTOR_ID, 
			name:result[i].ACTOR_NAME, 
			open:true, 
			isParent:true, 
			'type':result[i].ACTOR_TYPE});
	}

	$("#userSelectorWin").window({
		collapsible:false,
		title:'人员选择',
	    width:600,    
	    height:360, 
		left:($(window).width()-600)/2,
		top:($(window).height()-360)/2+$(window).scrollTop(),
	    modal:true  
	});
}

function delUser(){
	/*
	var row = $('#selUserTable').datagrid('getSelected');
	$('#selUserTable').datagrid('deleteRow', row.index);
	*/
	var row = $('#selUserTable').datagrid('getSelected');
	var isSign = false;
	if (!row) {
		row = $('#signleSelUserTree').datagrid('getSelected');
		isSign = true;
	}
	if(row) { 
		if (isSign) {
			$('#signleSelUserTree').datagrid('deleteRow',targetIndex);
		} else {
			$('#selUserTable').datagrid('deleteRow',targetIndex);
		}
	} else {
		$.messager.alert('提示','请选择一条记录!');
	}
}

function delAllUser(){
	/*
	var rows = $("#selUserTable").datagrid('getRows');
	$.each(rows, function(i, val){
		$("#selUserTable").datagrid('deleteRow',i);
	});
	*/
	clearAll();
}

function saveNextUser(){
	var ids = '';
	var names = '';
	var rows = $("#selUserTable").datagrid('getRows');
	if(nodeType == 'chargeBug'||nodeType == 'exDemand'||nodeType == 'exDemand_isChangeAdmin_1'||nodeType == 'costConfirmPerson'||nodeType == 'org'){
		if(rows.length > 1) {
			$.messager.alert('提示','只能选择一个对象!');
		} else {
			$.each(rows, function(i, val){
				ids += val.userId+',';
				names += val.partyName+',';
			});
			if(nodeType == 'costConfirmPerson'||nodeType == 'org'){
				document.getElementById(hiddenId).value = ids.substring(0, ids.length-1);
				document.getElementById(fileldId).value = names.substring(0, names.length-1);
			}else{
				$('#'+hiddenId).val(ids.substring(0, ids.length-1));
				$('#'+hiddenId).attr("start","1");
				$('#'+fileldId).val(names.substring(0, names.length-1));
			}
			
		}
		
	}else {
		$.each(rows, function(i, val){
			ids += val.userId+',';
			names += val.partyName+',';
		});
		
		$('#'+hiddenId).val(ids.substring(0, ids.length-1));
		$('#'+hiddenId).attr("start","1");
		$('#'+fileldId).val(names.substring(0, names.length-1));
	}
	if(_callback){
		_callback();
		try{
			eval(_callback+"()");
		}catch(e){
			
		}
	}
	closeWin(); 
	
}

//关闭窗口
function closeWin(){
	$("#userSelectorWin").window('close'); 
	clearAll();
}
	

$(function(){
	$("#userSelectorWin").window('close'); 
	$("#signleUserWin").window('close');
		
	//用户列表
	$("#userTable").datagrid({
		title:'人员列表',
		nowrap:false,
		fit: true,//自动大小
		border:false,
		method:'post',
		singleSelect:true,
		rownumbers:true,
		//url : "ztreePlatform.shtml?method=userList",
		url : "platform/userList.shtml",
		idField:'id',
		onDblClickRow:function(rowIndex, rowData){
			var rows = $("#selUserTable").datagrid('getRows');
			if(isExistRow(rows, rowData.id)) {
				if(rowData.id){
					// 判断如果是chargeBug，只能选择一个人
					var data = $('#selUserTable').datagrid('getData');
					if (data.total >= 1 && nodeType == 'chargeBug') {
						$.messager.alert('提示','只能选择一个负责人!');
					} else {
						$("#selUserTable").datagrid('appendRow',{
						  	userId:rowData.id,
						  	partyName:rowData.nickName
					  	});
					}
				}
			}

		},
		columns:[[
		  	{field:'id',hidden:true},
          	{title:'用户名称',field:'nickName', width:'140',align:'center'}

		]],
		queryParams:{
			'type':'1',
			'orgType':$("#orgType").val()
		}
	});

	//已选择用户列表
	$("#selUserTable").datagrid({
		title:'已选择人员',
		nowrap:false,
		fit: true,//自动大小
		border:false,
		method:'post',
		singleSelect:true,
		rownumbers:true,
		url : "",
		idField:'userId',
		columns:[[
		  	{field:'userId',hidden:true},
          	{title:'用户名称',field:'partyName',width:'140',align:'center'}
		]],
		queryParams:{
			'type':'1'
		},
		onClickRow: function(rowIndex,rowData){
			targetIndex = rowIndex;
		},
		onDblClickRow:function(rowIndex, rowData){
			$("#selUserTable").datagrid('deleteRow',rowIndex);
		}
	});
	/*
	//快速定位
	$("#promoter").click(function(){
		var rows = $("#selUserTable").datagrid('getRows');
		if($(this).attr('checked')){
			if(isExistRow(rows, $(this).attr('userId'))) {
				$("#selUserTable").datagrid('appendRow',{
				  	userId:$(this).attr('userId'),
				  	partyName:$(this).attr('userName')
			  	});
			}
		} else {
			deleteRow("#selUserTable", rows, $(this).attr('userId'));
		}
	});*/
});




function deleteRow(tableId, rows, uId){
	$.each(rows, function(i, val){
		if(val.id == uId){
			var index = $(tableId).datagrid('getRowIndex', val);
			$(tableId).datagrid('deleteRow', index);
			
		}
	});
}

function isExistRow(rows, uId){
	var tag = true;
	$.each(rows, function(i, val){
		if(val.id == uId){
			tag = false;
		}
	});
	return tag;
}



/**********************************用户人员选择面板**********************************/

//打开人员选择面板
function openSignleUserWin(result){
	if(_nodeId != $("#nodeId").val()){
		$("#signleUserTree").datagrid('reload');
		$("#signleSelUserTree").datagrid('reload');
	}
	
	$('#signleUserTree').datagrid('loadData', { total: 0, rows: [] });
	
	for(var i=0; i < result.length; i++){
		$("#signleUserTree").datagrid('appendRow',{
		  	userId:result[i].ACTOR_ID,
		  	partyName:result[i].ACTOR_NAME
	  	});
	}

	$("#signleUserWin").window({
		collapsible:false,
		title:'人员选择',
	    width:600,    
	    height:340, 
		left:($(window).width()-600)/2,
		top:($(window).height()-340)/2+$(window).scrollTop(),
	    modal:true  
	}); 
}

//保存人员选择面板
function signleSaveNextUser(){
	var ids = '';
	var names = '';
	
	var rows = $("#signleSelUserTree").datagrid('getRows');

	$.each(rows, function(i, val){
		ids += val.userId+',';
		names += val.partyName+',';
	});

	//$("#signleUserWin").window('close'); 
	$('#'+hiddenId).val(ids.substring(0, ids.length-1));
	$('#'+hiddenId).attr("start","1");
	$('#'+fileldId).val(names.substring(0, names.length-1));
	signleCloseWin();
}

//关闭人员选择面板
function signleCloseWin(){
	$("#signleUserWin").window('close'); 
	clearAll();
}

$(function(){
	//用户列表
	$("#signleUserTree").datagrid({
		title:'人员列表',
		nowrap:false,
		border:false,
		fit: true,//自动大小
		method:'post',
		singleSelect:true,
		rownumbers:true,
		idField:'userId',
		onDblClickRow: function(rowIndex, rowData){

			var rows = $("#signleSelUserTree").datagrid('getRows');
			if(isExistRow(rows, rowData.userId)) {
				$("#signleSelUserTree").datagrid('appendRow',{
				  	userId:rowData.userId,
				  	partyName:rowData.partyName
			  	});
			}

		},
		columns:[[
		  	{field:'userId',hidden:true},
          	{title:'用户名称',field:'partyName', width:'200',align:'center'}

		]]
	});

	//已选择用户列表
	$("#signleSelUserTree").datagrid({
		title:'已选择人员',
		nowrap:false,
		border:false,
		fit: true,//自动大小
		method:'post',
		singleSelect:true,
		rownumbers:true,
		//url : "",
		idField:'userId',
		columns:[[
		  	{field:'userId',hidden:true},
          	{title:'用户名称',field:'partyName',width:'200',align:'center'}
		]],
		onClickRow: function(rowIndex,rowData){
			targetIndex = rowIndex;
		},
		onDblClickRow:function(rowIndex, rowData){
			$("#signleSelUserTree").datagrid('deleteRow',rowIndex);
		}
	});
	
	/*
	$("#signlePromoter").click(function(){
		var rows = $("#signleSelUserTree").datagrid('getRows');
		if($(this).attr('checked')){
			if(isExistRow(rows, $(this).attr('userId'))) {
				$("#signleSelUserTree").datagrid('appendRow',{
				  	userId:$(this).attr('userId'),
				  	partyName:$(this).attr('userName')
			  	});
			}
		} else {
			deleteRow("#signleSelUserTree", rows, $(this).attr('userId'));
		}
	});
	*/
});

//添加
function addCheckUser() {
	var row = $('#userTable').datagrid('getSelected');
	var data=$('#selUserTable').datagrid('getData');
	var isSignle = false;
	if(!row) {
		isSignle = true;
		row = $('#signleUserTree').datagrid('getSelected');
		data=$('#signleSelUserTree').datagrid('getData');
	}
	if(row){
		
		if (isSignle) {
			var userId = row.userId;
			if (userId) {
				var partyName = row.partyName; 
				var falg = true;
				for(i=0; i<data.rows.length; i++){
					var drow = data.rows[i];
					if(drow.userId == userId) {
						falg = false;
						$.messager.alert('提示','该用户已添加过!');
						break;
					}
				}
				if (falg) {
					$('#signleSelUserTree').datagrid('appendRow',{
						userId: userId,
					  	partyName: row.partyName
					});
				}
			} 
		}else{
			var userId = row.id;
			if (userId) {
				var partyName = row.nickName; 
				var falg = true;
				for(i=0; i<data.rows.length; i++){
					var drow = data.rows[i];
					if(drow.id == userId) {
						falg = false;
						$.messager.alert('提示','该用户已添加过!');
						break;
					}
				}
				if (falg) {
					$('#selUserTable').datagrid('appendRow',{
						userId: userId,
					  	partyName: partyName
					});
				}
			} 
		}
	} else{
		$.messager.alert('提示','请选择一条记录!');
	}
}

/**
 * 清空选中表
 */
function clearAll() {
	$('#userTable').datagrid('loadData', { total: 0, rows: [] });
	$('#selUserTable').datagrid('loadData', { total: 0, rows: [] });
	$('#signleSelUserTree').datagrid('loadData', { total: 0, rows: [] });
}

//将saveForm中的usernames对应到已选人员选择面板
function setSelUser() {
	var userIds = '';
	var userNames = '';
	if(nodeType == 'costConfirmPerson'){
		userIds = document.getElementById(hiddenId).value;
		userNames = document.getElementById(fileldId).value;
	}else{
		userIds = $("#"+hiddenId).val();
		userNames = $("#"+fileldId).val();
	}
	
	//var userIds = $("#"+hiddenId).val();
	//var userNames = $("#"+fileldId).val();
	if(userIds != "" && userNames != ""&&userIds != undefined && userNames != undefined) {
		var arr_userIds = userIds.split(",");
		var arr_userNames = userNames.split(",");
		for(var i=0; i<arr_userIds.length; i++) {
			$('#selUserTable').datagrid('appendRow',{
				userId: arr_userIds[i],
				partyName : arr_userNames[i]
			});
		}
	}
}
function setSelSignUser() {
	var userIds = $("#"+hiddenId).val();
	var userNames = $("#"+fileldId).val();
	if(userIds != "" && userNames != "") {
		var arr_userIds = userIds.split(",");
		var arr_userNames = userNames.split(",");
		for(var i=0; i<arr_userIds.length; i++) {
			$('#signleSelUserTree').datagrid('appendRow',{
				userId: arr_userIds[i],
				partyName : arr_userNames[i]
			});
		}
	}
}
//快速定位
function fastSearch(){
	
	$('#userTable').datagrid('reload',{
		'nickName' : $('input[name=fastSearchTxt]').val(),
		'orgType':$("#orgType").val()
	});
	
}


function searchInputFocus() {
	$("#fastSearchTxt").val("");
}
	
function searchInputBlur() {
	$("#fastSearchTxt").val("请输入人员姓名或者帐号...");
}

function fastSearchUser() {
	var fastSearchTxt = $("#fastSearchTxt").val();
	var orgType = $("#orgType").val();
	if(fastSearchTxt==null || fastSearchTxt=="") {
		$("#fast_user_div").hide();
		return;
	} else {
		$("#fast_user_div").html("数据加载中...");
		$("#fast_user_div").show();
		$.post("ztreePlatform.shtml?method=queryUsersByName&t="+Math.random(), 
				{
					nickName : fastSearchTxt,
					orgType:orgType
				}, 
				function(data) {
					if(data.length>0) {
						var itemsHtml = '<table width="100%" class="select-table">';
						for(var i=0; i<data.length; i++) {
							if("org"==orgType){
								itemsHtml += '<tr height="28px" style="cursor:pointer" ondblclick="itemSelected('+data[i].id+',\''+data[i].id+','+data[i].name+'\')">';
								itemsHtml += '<td class="select-td" >'+data[i].name+'</td>';
								itemsHtml += '</tr>';
							}else{
								itemsHtml += '<tr height="28px" style="cursor:pointer" ondblclick="itemSelected('+data[i].orgId+',\''+data[i].id+','+data[i].nickname+'\')">';
								itemsHtml += '<td class="select-td" >'+data[i].nickname+'</td>';
								itemsHtml += '</tr>';
							}
						}
						itemsHtml += '</table>';
						$("#fast_user_div").html(itemsHtml);
					} else {
						$("#fast_user_div").html("<table width='100%'><tr><td><span style='color:red;'>没有找到相应数据</span></td><td><a href='javascript:void(0)' onclick='hideFastUser()'>关闭</a></td></tr></table>");
					}
				}, 
				"json");
	}
}

function itemSelected(orgId,userIdName) {
	userId = userIdName.split(",")[0];
	userName = userIdName.split(",")[1];
	var data=$('#selUserTable').datagrid('getData');
	var falg = true;
	for(i=0; i<data.rows.length; i++){
		var drow = data.rows[i];
		if(drow.userId == userId) {
			falg = false;
			$.messager.alert('提示','该用户已添加过!');
			break;
		}
	}
	if(falg) {
		$('#selUserTable').datagrid('appendRow',{
			userId: userId,
			orgId: orgId,
		  	partyName: userName
		});
	}
	$("#fast_user_div").hide();
}

function hideFastUser() {
	$("#fast_user_div").hide();
}

function displayFastUser() {
	$("#fast_user_div").show();
}

</script>
